package com.six.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.six.exception.CustomerException;
import com.six.mapper.AdminMapper;
import com.six.pojo.Admin;
import com.six.pojo.Menu;
import com.six.pojo.dto.LoginDto;
import com.six.result.MessageCode;
import com.six.service.AdminService;
import com.six.service.MenuService;
import com.six.utils.Md5Utils;
import com.six.utils.TokenUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
@Transactional
@Slf4j
public class AdminServiceImpl extends ServiceImpl<AdminMapper, Admin> implements AdminService {

    @Autowired
    private MenuService menuService;

    @Override
    public String login(LoginDto loginDto) {
        // 使用用户名查询用户信息
        LambdaQueryWrapper<Admin> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.eq(Admin::getUsername,loginDto.getUsername());
        Admin admin = getBaseMapper().selectOne(lambdaQueryWrapper);
        if(admin==null){
            log.info("用户名不存在!");
            throw new CustomerException(MessageCode.USERNAME_OR_PASSWORD_ERROR);
        }
        //2.获取盐，对用户输入的密码进行再次的加密
        String md5Password = Md5Utils.md5Password(loginDto.getPassword(), admin.getSalt());

        //3.对比密码是否一致，一致登录成功
        if(!md5Password.equals(admin.getPassword())){
            log.info("密码错误!");
            throw new CustomerException(MessageCode.USERNAME_OR_PASSWORD_ERROR);
        }

        // 4. 查询管理员对应的权限放到jwt当中
        List<Menu> menuList=menuService.findPermissionByAdminUsername(admin.getUsername());
        StringBuilder stringBuilder = new StringBuilder();
        menuList.forEach(menu -> {
            stringBuilder.append(menu.getPerms()+",");
        });
        //5.登录成功后，生成jwt令牌，返回给客户端
        //String token = TokenUtils.token(admin.getId(),admin.getName(), admin.getPhone(), admin.getImage(), admin.getUsername(),stringBuilder.toString());

        return null;
    }
}
